import { Component, ViewChild } from '@angular/core';
import { Events,AlertController, App, ModalController, NavController, Content, NavParams, ActionSheetController } from 'ionic-angular';
import { AuthorizationListService } from './list.service';
import { Config } from '../../../providers/config';
import { AuthorizationDetailPage } from '../detail/detail.component';

import _ from 'lodash';

@Component({
  selector: 'page-authorization-list',
  templateUrl: './list.html',
  providers: [AuthorizationListService]
})
export class AuthorizationListPage {
	moa_page_name: any = "page-authorization-list";
  moa_page_explain = "工作授权";

  _ = _;
  // 列表数据
  listData = [];

  // 是否可以加载更多
  isLoadMore = true;
  // 页码
  pageIndex = 1;

  // 历史授权列表和授权列表共用一个页面；值为 'hisPage' 历史授权列表, 其余值为授权列表
  whichPage

  // 接口请求参数
  params = {
    "needRenewAPI": true,  // true 调用接口数据，false 使用缓存数据
    "needSearch": false, // true 结合nameCondition进行查询， false 不查询
    "isHis": false, // 默认用false , true 历史授权记录
    "nameCondition": "", // 查询条件： 授权人 或 被授权人的名字
    "page": 1 // 查询第几页
  }

  @ViewChild(Content) content: Content;

  constructor(
    public alertCtrl: AlertController,
    public app: App,
    public modalCtrl: ModalController,
    public navCtrl: NavController,
    public actionSheetCtrl: ActionSheetController,
    public navParams: NavParams,
    public authorizationListService: AuthorizationListService,
    public config: Config,
    public events:Events
  ) {

    this.whichPage = this.navParams.get("whichPage");
    if(this.whichPage == "hisPage") { // 历史授权
      this.params.isHis = true;
      this.moa_page_explain = "历史授权";
    } else { // 工作授权
      this.params.isHis = false;
      this.moa_page_explain = "工作授权";
    }

    this.loadListData(null, null);

    this.events.unsubscribe("authorization-list-doRefresh");
    // 启动监听，如果有新增、编辑和删除操作则刷新列表
    this.events.subscribe("authorization-list-doRefresh", data => {
      if (data == null){ // 刷新列表
        this.doRefresh(null);
      } else if(data["type"]=="update"){ // 更新列表对象
        // 如果没有更新时间，则不刷新列表
        var index = _.findIndex(this.listData,{"numb": data["item"].numb});
        this.listData[index] = data["item"];
      } else if(data["type"] == "delete"){ // 移除列表对象
        //_.remove(this.listData,{"numb": data["item"].numb});
        this.search(true); // 刷新
      }

    });
  }
  /**
   * [loadListData 加载列表数据]
   * @param {[type]} page           [页码]
   * @param {[type]} title          [标题关键字]
   * @param {[type]} infiniteScroll [加载更多组件]
   * @param {[type]} refresher      [下拉刷新组件]
   */
  loadListData(infiniteScroll, refresher) {

    this.authorizationListService.getListData(this.params).subscribe(data => {
      if (data) {
        console.log("##authorization.list.loadListData -> data:");
        // 如果加载第一页，则清空数据
        if (this.params.page == 1) {
          this.isLoadMore = true;
          this.listData = [];
        }
        // 添加是否选中属性
        this.addIsChecked(data);
        // 把现有数据和新加载的数据合并
        this.listData = _.concat(this.listData, data);
        //console.info(this.listData);
        // 增加搜索索引
        this.pageIndex = this.pageIndex + 1;
        // 如果返回数据少于请求页数，则不再加载更多
        if (data.length < this.config.pageSize) {
          this.isLoadMore = false;
        }
      } else {
        this.listData = [];
        this.isLoadMore = false;
      }
      // complete event
      if (infiniteScroll) {
        infiniteScroll.complete();
      }
      if (refresher) {
        refresher.complete();
      }
    })
  };

  /**
   * [addIsChecked 初始化对象中添加是否选中属性]
   * @param {[type]} datas [description]
   */
  addIsChecked(datas) {
    _.forEach(datas, function(data) {
      data.isChecked = false;
    })
  }

  /**
   * [iocnCheck 实现单选效果]
   * @param {[type]} item [description]
   */
  iocnCheck(item) {
    //console.log("##autorization.iocnCheck:" + item.isChecked);
    // 实现单选
    var stat = item.isChecked;
    if (stat == false) {
      _.forEach(_.filter(this.listData, { "isChecked": true }), function(data) {
        data.isChecked = false;
      })
    }

    item.isChecked = !stat;
  }


  /**
   * [goDetailPage 跳转详情页]
   * @param {[type]} item [参数]
   */
  goDetailPage(item) {
    let detial = this.params.isHis? "detialHis" : "detail";
    this.navCtrl.push(AuthorizationDetailPage, { "item": item, "type": detial }); // "type": add 新增， update 编辑 ，detail详情， detialHis历史详情
  };

  ionViewDidLoad() {

  };

  do() {
    var that = this;
    let actionSheet = this.actionSheetCtrl.create({
      title: "",
      buttons: [
        {
          text: "增加授权配置",
          handler: () => {
            that.navCtrl.push(AuthorizationDetailPage, { "item": {}, "type": "add" });
          }
        },
        {
          text: "删除授权配置",
          handler: () => {
            this.delete();
          }
        },
        // {
        //   text: "个人历史授权记录",
        //   handler: () => {
        //     this.navCtrl.push(AuthorizationListPage,{"whichPage" : "hisPage"});
        //   }
        // },
        {
          text: "取消",
          role: 'cancel',
          handler: () => {
          }
        }
      ]
    });

    actionSheet.present();
  }

  /**
   * [delete 删除授权]
   */
  delete() {
    var item = _.filter(this.listData, { "isChecked": true });
    console.log("##authorization.delete 删除对象：");
    console.log(item[0]);
    if (item.length == 0) {
      let alert = this.alertCtrl.create({
        title: "提示",
        message: "请选择一个工作授权再删除！",
        buttons: [
          {
            text: "确定",
            role: 'cancel',
            handler: () => {
            }
          }
        ]
      });
      alert.present();
    } else {
      this.authorizationListService.deleteAuthorization(item[0].numb).subscribe(data => {
        if (data["code"] == "0") {
          let alert = this.alertCtrl.create({
            title: "提示",
            message: "删除成功",
            buttons: [
              {
                text: "确定",
                role: 'cancel',
                handler: () => {
                  //_.pullAll(this.listData,item);
                  this.search(true); // 刷新
                }
              }
            ]
          });
          alert.present();
        } else {
          let alert = this.alertCtrl.create({ // 有异常信息，弹出提示
            title: "提示",
            message: "删除失败",
            buttons: [
              {
                text: "确定",
                role: 'cancel',
                handler: () => {
                }
              }
            ]
          });
          alert.present();
        }
      })
    }
  }
  /**
   * [search 进入列表页面时会请求一次接口然存缓存数据；当执行查询时，不离开页面时则在缓存中查询]
   */
  search(needRenewAPI?) {
    this.content.scrollToTop(); // 将滚动的位置重新置顶
    this.params.needRenewAPI = needRenewAPI? true : false; // 不需要再次请求接口，直接读缓存数据
    this.params.needSearch = true; // 执行查询动作
    this.params.page = 1;
    this.isLoadMore = true;

    this.loadListData(null, null);
  }

  /**
   * [doInfinite 加载更多]
   * @param {[type]} infiniteScroll [事件]
   */
  doInfinite(infiniteScroll) {
    this.params.needRenewAPI = false;
    this.params.needSearch = false;
    if (this.pageIndex != 1) {
      if (this.isLoadMore) {
        this.params.page = this.pageIndex;
        this.loadListData(infiniteScroll, null);
      } else {
        infiniteScroll.complete();
      }
    }
  }
  /**
   * [doRefresh 下拉刷新]
   * @param {[type]} refresher [事件]
   */
  doRefresh(refresher) {
    this.params.needRenewAPI = true;
    this.params.needSearch = true;
    this.pageIndex = 1;
    this.isLoadMore = true;

    this.params.page = this.pageIndex;
    this.loadListData(null, refresher);
  }
}
